package com.pwt.utils;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.net.ProtocolException;
import java.nio.charset.StandardCharsets;
import java.util.*;


/**
 * Http请求相关工具类
 *
 * @author zhangzedong
 * @version 1.0.0
 * @date 2021/6/8
 */
@Component
@Slf4j
public class HttpUtils2 {

    @Autowired
    private HttpClientUtils httpClientUtils;

    /**
     * 获取当前Http请求的客户端ip地址
     *
     * @param request
     * @return
     */
    public String getRemortIp(HttpServletRequest request) {
        String hed = "x-forwarded-for";
        if (request.getHeader(hed) == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader(hed);
    }

    /**
     * 获取当前请求的url地址
     *
     * @param request
     * @return
     */
    public String getRemortUrl(HttpServletRequest request) {
        return request.getRequestURL().toString();

    }

    /**
     * 获取当前请求的具体类和方法
     *
     * @param request
     * @return
     */
    public String getClassMethod(HttpServletRequest request, JoinPoint joinPoint) {
        return joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    }



    /**
     * 获取当前IP的归属地
     *
     * @param ip 当前IP
     * @return
     */
    public String getIpArea(String ip) {
        // 拼接访问地址+IP
        String url = "http://freeapi.ipip.net/" + ip;
        // 访问并返回数据
        JSONArray object = httpClientUtils.httpGet(url);
//        System.out.println(object);
        return object.get(1).toString() + "/" + object.get(2).toString();
    }


    /**
     * post请求
     *
     * @return 二进制数据
     */
    public static InputStream doPostBytes(String urlStr, String params) {
        URL url = null;// 创建连接
        try {
            url = new URL(urlStr);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        try {
            connection.setRequestMethod("POST"); // 设置请求方式
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
        connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
        try {
            connection.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        OutputStreamWriter out = null; // utf-8编码
        try {
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out.append(params);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            InputStream is = connection.getInputStream();
            return is;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * get请求
     *
     * @return 二进制数据
     */
    public static byte[] doGetBytes(String url) {
        try {
            HttpClient client = HttpClients.createDefault();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);


            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toByteArray(response.getEntity());
            } else {
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            log.error("请求["+url+"]失败",e);
        }
        return null;
    }

    /**
     * get请求
     *
     * @return 二进制数据
     */
    public static byte[] doGetBytes(String url, Map headParam, Map queryParam, Map<String,String> responseHeader) {
        try {
            HttpClient client = HttpClients.createDefault();
            //发送get请求
            StringBuilder sb = new StringBuilder(url);
            if(queryParam != null && queryParam.size() > 0) {
                sb.append("?");
                for (Iterator iter = queryParam.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String value = String.valueOf(queryParam.get(name));
                    sb.append(name).append("=").append(value).append("&");
                }
            }
            HttpGet request = new HttpGet(sb.toString());
            if(headParam != null && headParam.size() > 0) {
                for (Iterator iter = headParam.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String value = String.valueOf(headParam.get(name));
                    request.addHeader(name, value);
                }
            }
            HttpResponse response = client.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                Header[] headers = response.getAllHeaders();
                for(Header header:headers) {
                    responseHeader.put(header.getName(),header.getValue());
                }
                return EntityUtils.toByteArray(response.getEntity());
            } else {
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            log.error("请求["+url+"]失败",e);
        }
        return null;
    }

    /**
     * get请求
     *
     * @return
     */
    public static Map doGetContent(String url) {
        Map<String,Object> map = new HashMap<>();
        try {
            HttpClient client = HttpClients.createDefault();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                Header[] headers = response.getHeaders("content-type");
                map.put("content-type",headers[0].getValue());
                map.put("content", EntityUtils.toByteArray(response.getEntity()));
                return map;
            } else {
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            log.error("请求["+url+"]失败",e);
        }
        return null;
    }

    /**
     * get请求
     *
     * @return json串
     */
    public static String doGet(String url) {
        try {
            HttpClient client = HttpClients.createDefault();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                return EntityUtils.toString(response.getEntity());
            } else {
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            log.error("请求["+url+"]失败",e);
        }
        return null;
    }

    /**
     * get请求
     *
     * @return json串
     */
    public static String doGet(String url,Map headParam,Map queryParam) {
        try {
            HttpClient client = HttpClients.createDefault();
            //发送get请求
            StringBuilder sb = new StringBuilder(url);
            if(queryParam != null && queryParam.size() > 0) {
                sb.append("?");
                for (Iterator iter = queryParam.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String value = String.valueOf(queryParam.get(name));
                    sb.append(name).append("=").append(value).append("&");
                }
            }
            url = sb.toString();
            HttpGet request = new HttpGet(url);
            if(headParam != null && headParam.size() > 0) {
                for (Iterator iter = headParam.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String value = String.valueOf(headParam.get(name));
                    request.addHeader(name, value);
                }
            }
            HttpResponse response = client.execute(request);
            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                return EntityUtils.toString(response.getEntity());
            } else {
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            log.error("请求["+url+"]失败",e);
        }
        return null;
    }

    /**
     * post请求(用于key-value格式的参数)
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map params) {

        BufferedReader in = null;
        // 定义HttpClient
        HttpClient client = HttpClients.createDefault();
        try {
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));

            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));

            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            //请求成功
            if (code == HttpStatus.SC_OK) {
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String nl = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line).append(nl);
                }

                return sb.toString();
            } else {   //
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
                return null;
            }
        } catch (Exception e) {
            log.error("请求["+url+"]失败",e);

            return null;
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("请求["+url+"]失败",e);
                }
            }
        }
    }
    /**
     * post请求(用于key-value格式的参数)
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url,Map headParam, Map params) {

        BufferedReader in = null;
        // 定义HttpClient
        HttpClient client = HttpClients.createDefault();
        try {
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));
            request.setHeader("Content-Type","application/json");
            if(headParam != null) {
                for (Iterator iter = headParam.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String value = String.valueOf(headParam.get(name));
                    request.addHeader(name, value);
                }
            }
            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));
            }

            request.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));

            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            //请求成功
            if (code == HttpStatus.SC_OK) {
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String nl = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line).append(nl);
                }

                return sb.toString();
            } else {   //
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
                return null;
            }
        } catch (Exception e) {
            log.error("请求["+url+"]失败",e);

            return null;
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("请求["+url+"]失败",e);
                }
            }
        }
    }


    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) throws IOException {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json,text/html");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity);
            } else {
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("请求["+url+"]失败",e);
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error("请求["+url+"]失败",e);
            }
        }
        return null;
    }

    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params, Map headParam) throws IOException {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json,text/html");
        httpPost.setHeader("Content-Type", "application/json");
        if(headParam != null) {
            for (Iterator iter = headParam.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String value = String.valueOf(headParam.get(name));
                httpPost.addHeader(name, value);
            }
        }
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity);
            } else {
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("请求["+url+"]失败",e);
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error("请求["+url+"]失败",e);
            }
        }
        return null;
    }




    /**
     * 发送带有xml参数的post请求
     * @param url
     * @param xmlParams
     * @return
     * @throws IOException
     */
    public static String doPostXml(String url, String xmlParams) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String charSet = "UTF-8";
        httpPost.setEntity(new StringEntity(xmlParams, "UTF-8"));
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity);
            } else {
                log.error("请求{}失败，返回值：{}",url,response.getStatusLine().getStatusCode());
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("请求["+url+"]失败",e);
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error("请求["+url+"]失败",e);
            }
        }
        return null;
    }
}
